//
//  MineNewsController.m
//  Coach_HaiGeEr
//
//  Created by liuchen on 2018/9/13.
//  Copyright © 2018年 海格尔. All rights reserved.
//

#import "MineNewsController.h"
#import "UIViewController+Ext.h"
#import "NewsCell.h"
#import "NewsInfoController.h"
#import "MJRefresh.h"

@interface MineNewsController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSInteger page;
    NSInteger size;
}
@property (nonatomic, strong) UIImageView *dataImageView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *listDataArr;
@end

@implementation MineNewsController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[CoachTabBarController shareLZHTabbarController].tabBar setHidden:YES];
    [self reloadMessage];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.navigationItem.title = @"我的消息";
    [self setNavBack];
    [self setNewsAllRead];
    page = 1;
    self.listDataArr = [[NSMutableArray alloc] init];
    
    _tableView = [[UITableView alloc] init];
    _tableView.delegate = self;
    _tableView.dataSource  = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    [_tableView setSeparatorInset:UIEdgeInsetsMake(0, 30*SCALEUNIT, 0, 30*SCALEUNIT)];
    [_tableView setSeparatorColor:[UIColor colorWithHexString:@"#eeeeee"]];
    [self.view addSubview:_tableView];
    
    [self initNoDataBG];
    
    WS(ws);
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ws.view);
        make.right.equalTo(ws.view);
        make.top.equalTo(ws.view);
        make.bottom.equalTo(ws.view);
    }];
    
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self reloadMessage];
    }];
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self getMoreNews];
    }];
}

#pragma mark - 设置导航右按钮
- (void)setNewsAllRead
{
    UIButton *tempButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60 * SCALING, 20 * SCALING)];
    [tempButton.titleLabel setFont:[UIFont systemFontOfSize:LoginFont-2]];
    [tempButton setTitle:@"全部已读" forState:UIControlStateNormal];
    [tempButton setTitleColor:[UIColor colorWithRed:22/255.0f green:174/255.0f blue:149/255.0f alpha:1.0f]
                     forState:UIControlStateNormal];
    [tempButton addTarget:self
                   action:@selector(newsAllRead)
         forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:tempButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;
}

#pragma mark -
- (void)initNoDataBG
{
    CGRect userIFrame = CGRectMake((CGRectGetWidth(self.view.frame)-180 * SCALING) / 2.0f,
                                   (CGRectGetHeight(self.view.frame)-140 * SCALING) / 2.0f,
                                   180 * SCALING,
                                   140 * SCALING);
    _dataImageView = [[UIImageView alloc] initWithFrame:userIFrame];
    [_dataImageView setImage:[UIImage imageNamed:@"no_data_bg"]];
    [self.view addSubview:_dataImageView];
}

#pragma mark - 表格数据处理
#pragma mark - TableViewDelegate
//指定有多少个分区(Section)，默认为1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;//返回标题数组中元素的个数来确定分区的个数
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listDataArr.count;
}

//改变cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 86 * SCALING;
}
//绘制Cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"NewsTableViewCell";
    NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {//说明可重用队列里面并cell，此时需要重新创建cell实例，采用下面方法
        cell = [[NewsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.newsModels = _listDataArr[indexPath.row];
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NewsInfoController *tempController = [[NewsInfoController alloc] init];
    tempController.newsModels = _listDataArr[indexPath.row];
    tempController.block = ^{
        [self reloadMessage];
    };
    [self.navigationController pushViewController:tempController animated:YES];
}

#pragma mark - 获取消息
- (void)setMoreFooterStatus:(NSInteger)totalPages
{
    if (page >= totalPages) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    else {
        [self.tableView.mj_footer resetNoMoreData];
    }
}

- (void)reloadMessage
{
    [self showLoading];
    [self.listDataArr removeAllObjects];
    page = 1;
    size = 50;
    [self messageList:page size:size success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSInteger status = [[responseObject objectForKey:@"code"] integerValue];
            if (status == 1) {
                NSArray *data = [responseObject objectForKey:@"data"];
                if ([data isKindOfClass:[NSArray class]]) {
                    for (NSDictionary *tempDict in data) {
                        NewsModels *newsModel = [[NewsModels alloc] initWithDict:tempDict];
                        [self.listDataArr addObject:newsModel];
                    }
                }
                [self setMoreFooterStatus:[[[responseObject objectForKey:@"pageInfo"] objectForKey:@"totalPages"] integerValue]];
            }
            else if (status == 2) {
                [self toLoginVC];
            }
        }
        if (self.listDataArr.count > 0) {
            [self.dataImageView setHidden:YES];
        }
        else {
            [self.dataImageView setHidden:NO];
        }
        [self.tableView reloadData];
        [self hideHUD];
    } failure:^(NSString *error) {
        [self hideHUD];
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)getMoreNews
{
    [self showLoading];
    page ++;
    [self messageList:page size:size success:^(id responseObject) {
        [self.tableView.mj_footer endRefreshing];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSInteger status = [[responseObject objectForKey:@"code"] integerValue];
            if (status == 1) {
                NSArray *data = [responseObject objectForKey:@"data"];
                if ([data isKindOfClass:[NSArray class]]) {
                    for (NSDictionary *tempDict in data) {
                        NewsModels *newsModel = [[NewsModels alloc] initWithDict:tempDict];
                        [self.listDataArr addObject:newsModel];
                    }
                }
                [self setMoreFooterStatus:[[[responseObject objectForKey:@"pageInfo"] objectForKey:@"totalPages"] integerValue]];
            }
            else if (status == 2) {
                [self toLoginVC];
            }
        }
        if (self.listDataArr.count > 0) {
            [self.dataImageView setHidden:YES];
        }
        [self.tableView reloadData];
        [self hideHUD];
    } failure:^(NSString *error) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        [self hideHUD];
    }];
}

#pragma mark - 事件处理
#pragma mark - 按钮事件处理
- (void)newsAllRead
{
    [self showLoading];
    [self messageRead:nil success:^(id responseObject) {
        [self hideHUD];
        NSDictionary *JSON = (NSDictionary *)responseObject;
        if ([JSON isKindOfClass:[NSDictionary class]]) {
            NSInteger status = [[JSON objectForKey:@"code"] integerValue];
            if (status == 1) {
                [self reloadMessage];
            }else if (status == 2) {
                [self toLoginVC];
            }
        }
    } failure:^(NSString *error) {
        [self showError:error];
    }];
}

#pragma mark - 我的消息相关请求
#pragma mark - 获取所有消息
- (void)messageList:(NSInteger)page
               size:(NSInteger)size
            success:(void (^)(id responseObject))success
            failure:(void (^)(NSString  *error))failure
{
    NSString *postURL = @"/authc/message/list";
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                [NSNumber numberWithInteger:page], @"page",
                                [NSNumber numberWithInteger:size], @"size", nil];
    [[NetworkEngine sharedClient] GETByToken:postURL
                                 data:parameters
                              success:^(id responseObject) {
                                  if (success) {
                                      success(responseObject);
                                  }
                              }
                              failure:^(NSString *error) {
                                  if (failure) {
                                      failure(error);
                                  }
                              }];
}

#pragma mark 获取所有未读消息数
- (void)messageNumber:(void (^)(id responseObject))success
              failure:(void (^)(NSString  *error))failure
{
    NSString *postURL = @"/authc/message/unRead";
    [[NetworkEngine sharedClient] GETByToken:postURL data:nil success:^(id responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSString *error) {
        if (failure) {
            failure(error);
        }
    }];
}

#pragma mark 消息标记为已读
- (void)messageRead:(NSNumber *)message_id
            success:(void (^)(id responseObject))success
            failure:(void (^)(NSString  *error))failure
{
    NSString *postURL = @"/authc/message/read";
    [[NetworkEngine sharedClient] POSTByToken:postURL
                                  data:nil
                               success:^(id responseObject) {
                                   if (success) {
                                       success(responseObject);
                                   }
                               }
                               failure:^(NSString *error) {
                                   if (failure) {
                                       failure(error);
                                   }
                               }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
